// 存储webSocket的状态
import { defineStore } from 'pinia'
import { WebSocketConstructor } from '@/utils/webSocket'
import { getChatRecordApi , sendMessageApi ,getOneByOneApi} from '@/api/webSocket/webSocket'

export const useWebSocketStore = defineStore('webSocket', () => {
  //存储webSocket的状态,供消息组件使用
  const webSocket: any = reactive({})
  // 临时存储消息列表
  const messageLists: any = ref(null)
  const messageList: any = ref(null)
  function createWebSocket(username: string) {
    return new Promise<void>((_, reject) => {
      const ws = new WebSocketConstructor(username)      
      if(ws){
        webSocket.value = ws
      }else{
        reject('WebSocket连接失败！')
      }
    })
  }

  // 关闭
  function closeWebSocket() {
    webSocket.value.close()
    webSocket.value = null
    console.log('WebSocket已关闭！',webSocket);
  }

  // 获取聊天记录
  function getChatRecord() {
    return getChatRecordApi();
  }

  // 发送消息
  function sendMessage(message: string) {
    // 发送消息
    console.log(webSocket.value);
    
    webSocket.value.sendMsg(message)
    return sendMessageApi(message);
  }

  // 获取一对一聊天人信息
  function getOneByOne(data: any) {
    return getOneByOneApi(data);
  }

  return {
    webSocket,
    messageLists,
    messageList,
    createWebSocket,
    closeWebSocket,
    getChatRecord,
    sendMessage,
    getOneByOne
  }
})